package com.fimmlps.reronge.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

public class OssUtils {
    private static String endPoint = "oss-cn-beijing.aliyuncs.com";
    //访问id
    private static String accessKeyId = "LTAI5tFmqAFCEVUUXHh8jef2";
    //访问秘钥
    private static String accessKeySecret = "Dl8qRL9TF13M9MjmDnwbI2mSoYDjQT";
    //桶名称
    private static String bucketName = "reronge";
    //访问URL
    private static String url = "https://reronge.oss-cn-beijing.aliyuncs.com";

    public static String upload(String fileName, InputStream inputStream){
        OSS oss = new OSSClientBuilder().build(endPoint,accessKeyId,accessKeySecret);
        String objectName = "images/" + new SimpleDateFormat("yyyy/MM/dd").format(new Date()) + "/" + System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf("."));

        ObjectMetadata meta = new ObjectMetadata();
        meta.setContentType(getContentType(fileName.substring(fileName.lastIndexOf("."))));
        oss.putObject(bucketName,objectName,inputStream,meta);
        oss.shutdown();
        return url + "/" + objectName;
    }

    public static void delete(String url){
        OSS oss = new OSSClientBuilder().build(endPoint,accessKeyId,accessKeySecret);
    }

    public static String getContentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase(".bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase(".gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
                FilenameExtension.equalsIgnoreCase(".jpg") ||
                FilenameExtension.equalsIgnoreCase(".png")) {
            return "image/jpg";
        }
        return "image/jpg";
    }
}
